<?php
/**
 * Created by PhpStorm.
 * User: zhengze
 * Date: 2019/7/1
 * Time: 18:29
 */

namespace app\admin\validate;

use app\common\model\AdminStructure;
use app\api\enum\ScopeEnum;
use app\api\service\Token;
use common\exception\ExceptionEmun;
use common\exception\StructureException;
use common\traits\InstanceTrait;
use common\validate\BaseValidate;
use app\lib\exception\TokenException;

/**
 * Class StructureValidate
 */
class StructureValidate extends BaseValidate
{
    use InstanceTrait;

    protected $rule = [
        'id|参数' => ['require',],
        'ids|参数' => ['require',],
        'status|状态' => ['require',],
        'pid|父部门' => ['require',],
        'name|标题' => ['require',],
    ];

    protected $sceneRule = [
        'index' => [
            'only' => [''],
        ],
        'read' => [
            'only' => ['id'],
        ],
        'delete' => [
            'only' => ['id'],
        ],
        'deletes' => [
            'only' => ['ids'],
        ],
        'enables' => [
            'only' => ['ids', 'status'],
        ],
        'save' => [
            'only' => ['name'],
            'append' => [
                'name' => 'checkNameUnique',
                'pid' => 'checkPidRight',
            ],
        ],
        'update' => [
           'only' => ['name'],
           'append' => [
               'name' => 'checkNameUnique',
               'pid' => 'checkPidRight',
           ],
        ],
    ];

    /**
     * 检测父ID是否存在
     * @param $value
     * @return bool
     * @throws \Exception
     */
    protected function checkPidRight($value, $rule, $data = [])
    {
        //pid可以是零
        if (!empty($value)) {
            $AdminRule = AdminStructure::get($value);
            if (empty($AdminRule)) {
                return ExceptionEmun::getExctprion(StructureException::PID_NO_EXIST);
            }
        }
        return true;
    }

    /**
     * 检测名字重复
     * @param $value
     * @param $rule
     * @param array $data
     * @return bool
     * @throws \Exception
     */
    protected function checkNameUnique($value, $rule, $data = [])
    {
        $AdminStructure = AdminStructure::instance();
        $adminStructure = $AdminStructure->getByField('name', $value);
        $pk = 'id';
        if (!empty($adminStructure)) {
            if (!empty($data[$pk])) {
                //修改帐号
                if ($data[$pk] != $adminStructure['structure_id']) {
                    return ExceptionEmun::getExctprion(PostException::NAME_REPEAT);
                }
            } else {
//                创建帐号
                return ExceptionEmun::getExctprion(PostException::NAME_REPEAT);
            }
        }
        return true;
    }
}